package bankingSystemServer;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import communicationClasses.*;
import communicationClasses.TransactionRequest.TransactionType;

/**
 * a single thread implementation of Server
 */
public class SingleThreadServer extends Server {

	@Override
	public void receiveMessage(Object request, ObjectOutputStream out,
			ServerListeningThread thread) {
		try {
			if (request instanceof LoginRequest) {
				/**
				 * Handle login requests.
				 */
				LoginRequest loginRequest = (LoginRequest) request;
				String username = loginRequest.getName();
				String password = loginRequest.getPassword();
				if (login(username, password)) {
					User user = users.getUser(username);
					if (user == null) {
					} else {
						if (user instanceof Customer) {
							Customer customer = (Customer) user;
							out.writeObject(new TransactionReply(true, customer
									.getUserAccounts()));
						}
						if (user instanceof Admin) {
							out.writeObject(new TransactionReply(true, null));
						}
					}
				} else {
					out.writeObject(new TransactionReply(false, null));
				}
			}
			if (request instanceof TransactionRequest) {
				/**
				 * Handle transaction requests.
				 */
				TransactionRequest transactionRequest = (TransactionRequest) request;
				TransactionType type = transactionRequest.getType();
				int amount = transactionRequest.getAmount();
				if (preformTransaction(type, amount)) {
					
				} else {

				}
			}
			if (request instanceof TransferRequest) {
				/**
				 * Handle transfer requests.
				 */
				TransferRequest transferRequest = (TransferRequest) request;
				String from = transferRequest.getFromAccount();
				String to = transferRequest.getToAccount();
				int amount = transferRequest.getAmount();
				if (preformTransfer(from, to, amount)) {

				} else {

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Attempts a fund transfer.
	 * 
	 * @param from
	 * @param to
	 * @param amount
	 * @return Returns true if the transfer was successful.
	 */
	public boolean preformTransfer(String from, String to, int amount) {
		// TODO the actual implementation
		System.out.println("Transfering " + amount + " from " + from + " to "
				+ to);
		return false;	
	}



	/**
	 * Attempts to perform a transaction.
	 * 
	 * @param type
	 * @param amount
	 * @return Returns true if successful.
	 */
	public boolean preformTransaction(TransactionType type, int amount) {
		// TODO the actual implementation
		return false;
	}



	public static void main(String args[]) {
		SingleThreadServer server = new SingleThreadServer();
		server.addUser(new Customer("user", "123"));
		server.addUser(new Admin("admin", "admin"));
		server.addAccount("user", "asdf123", 1234);
		System.out.println(server.getUserStrings());
		server.run();
	}

}
